package com.jg.visitor.kafka.listener.normal;

import com.jg.visitor.kafka.consumer.KafkaMsgHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Properties;

@Slf4j
@Component
// * 批量消费 手动监听,          当前已关闭，            normal换个manually二选一
// * 如果要使用此配置initRunner里面调用此配置得listenKafka的方法即可，并且取消manually的配置
public class KafkaMsgListener {

    @Value("${spring.kafka.bootstrap-servers}")
    private String serverAddress;
    @Value("${spring.kafka.consume-topics}")
    private List<String> topics;
    @Value("${spring.kafka.consumer.group-id}")
    private String groupId;

    @Resource
    private Map<String, KafkaMsgHandler> handlerMap;

    public void listenKafka(){
        //创建消费者配置信息
        Properties properties = new Properties();

        //给配置信息赋值

        //连接的集群
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,serverAddress);

        //开启自动提交
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true);

        //自动提交的延时
        properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");

        //关闭自动提交
        //properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);

        //key,value的反序列化
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());

        //消费者组
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);

        //创建消费者
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);

        //订阅主题
        consumer.subscribe(topics);

        //获取数据

        while (true) {
            ConsumerRecords<String, String> consumerRecords = consumer.poll(Duration.ofMillis(100));

            //将数据丢给对应handler处理
            for (ConsumerRecord<String, String> consumerRecord : consumerRecords) {
                String topic = consumerRecord.topic();
                KafkaMsgHandler kafkaMsgHandler = handlerMap.get(topic);
                log.info("receive msg,topic={},handler ready? ==> {}",topic,kafkaMsgHandler != null);
                if(kafkaMsgHandler != null){
                    kafkaMsgHandler.onMsg(consumerRecord.value());
                }
            }
        }
    }
}
